<?php

/**
 * @Author: king
 * @Date:   2019-05-04 17:36:19
 * @Last Modified by:   king
 * @Last Modified time: 2019-05-05 16:17:06
 */
namespace App\Models\Api;
use App\Exceptions\ApiException;
use App\Models\Api\Base;
use Cache;

class LanmeiCourseSectionExercise extends Base
{
    protected $table = 'course_section_exercise';

    const COURSE_SECTION_EXERCISE_CISE = 'course:section:exercise:csid'; //章节练习ID
    const CACHE_TIME = 86400 * 7;

    /**
     * 通过章节ID 获取练习信息
     * @param $csid
     * @return array|bool|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getSectionExercise($csid)
    {
        $sectionExerciseData = false;

        if ($this->cache_on === 1 && Cache::has(self::COURSE_SECTION_EXERCISE_CISE . $csid))
        {
            $sectionExerciseData = Cache::get(self::COURSE_SECTION_EXERCISE_CISE . $csid);
        }

        if (!$sectionExerciseData)
        {
            try
            {
                // 获取数据
                $sectionExerciseDataModel = $this->where(['csid' => $csid, 'status' => 1])
                    ->select('title','title_img','optionA','optionB','optionC','optionD','answer','analysis')
                    ->get();
                // 返回数据格式化
                $sectionExerciseDataArray = collection($sectionExerciseDataModel)->toArray();

                $sectionExerciseData = json_encode($sectionExerciseDataArray);
                // 将章节练习内容写入缓存 判断是否开启缓存 并且数据不为空
                if (!empty($sectionExerciseDataArray) && $this->cache_on === 1)
                {
                    Cache::set(self::COURSE_SECTION_EXERCISE_CISE . $csid, $sectionExerciseData, self::CACHE_TIME);
                }
            }
            catch (\Exception $e)
            {
                $sectionExerciseData = '[]';
            }

        }

        return $sectionExerciseData;
    }
}
